package com.zadtek.shopmall.fragments;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.goyourfly.multi_picture.ImageLoader;
import com.goyourfly.multi_picture.MultiPictureView;
import com.zaaach.citypicker.model.City;
import com.zadtek.shopmall.R;
import com.zadtek.shopmall.activities.ChoosePicActivity;
import com.zadtek.shopmall.activities.MainActivity;
import com.zadtek.shopmall.base.AbsFragment;
import com.zadtek.shopmall.base.BaseActivity;
import com.zadtek.shopmall.bean.CarCity;
import com.zadtek.shopmall.bean.OperateResponseBean;
import com.zadtek.shopmall.bean.OperateResponseBean2;
import com.zadtek.shopmall.bean.UpLoadImgResponse;
import com.zadtek.shopmall.net.BaseObserver;
import com.zadtek.shopmall.net.BaseResponse;
import com.zadtek.shopmall.net.NetTool;
import com.zadtek.shopmall.utils.ToastUtil;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.MultipartBody;

import static android.app.Activity.RESULT_OK;

/**
 * Created by zack on 2018/5/31.
 */

public class CarFragment extends AbsFragment implements View.OnClickListener {
    private TextView tvPersonNum;
    private MultiPictureView multiPictureView;
    private List<String> choosePath = new LinkedList<>();
    private TextView et_departure;
    private TextView et_destination;
    private TextView et_time;
    private EditText et_info;
    private EditText et_name;
    private EditText et_phone;
    private TextView tv_publish;
    private List<CarCity> carCities = new LinkedList<>();
    // End Of Content View Elements

    @Override
    public int setView() {
        return R.layout.fragment_car1;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initView();
        initLogic();
        requestCity();
    }

    private void requestCity() {
        NetTool.getApi().getCarCity()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<List<CarCity>>>(this) {
                    @Override
                    public void onData(BaseResponse<List<CarCity>> value) {
                        if(value.getCode() == 0 && value.getData()!=null) {
                            carCities.addAll(value.getData());
                        }
                    }
                });
    }

    private void initLogic() {
        MultiPictureView.setImageLoader(new ImageLoader() {
            @Override
            public void loadImage(@NotNull ImageView image, @NotNull Uri uri) {
                Glide.with(mActivity).load(uri.getPath().substring(1)).into(image);
            }
        });
        tvPersonNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPicker();
            }
        });
        multiPictureView.setAddClickCallback(new MultiPictureView.AddClickCallback() {
            @Override
            public void onAddClick(@NotNull View view) {
                mActivity.performCodeWithPermission("需要照相权限", new BaseActivity.PermissionCallback() {
                    @Override
                    public void hasPermission() {
                        MultiImageSelector.create().showCamera(true).multi().count(6-choosePath.size()).start(CarFragment.this,200);
                    }
                    @Override
                    public void noPermission() {

                    }
                },new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA});
            }
        });
        multiPictureView.setDeleteClickCallback(new MultiPictureView.DeleteClickCallback() {
            @Override
            public void onDeleted(@NotNull View view, int index) {
                choosePath.remove(index);
                multiPictureView.removeItem(index);
            }
        });
        tv_publish.setOnClickListener(this);
        et_time.setOnClickListener(this);
        et_departure.setOnClickListener(this);
        et_destination.setOnClickListener(this);
    }

    private void showPicker() {
        final List<String> op1 = new ArrayList<>();

        OptionsPickerView pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = op1.get(options1);
                tvPersonNum.setText(tx);
                ToastUtil.showToast(tx);
            }
        }).setTitleText("人数")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x00000000) //设置外部遮罩颜色
                .build();
        op1.add("1人");
        op1.add("2人");
        op1.add("3人");
        op1.add("4人");
        pvOptions.setPicker(op1);
        pvOptions.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == 200){
            ArrayList<String> list = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
            NetTool.uploadFile(list)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<BaseResponse<UpLoadImgResponse>>(this) {
                        @Override
                        public void onData(BaseResponse<UpLoadImgResponse> value) {
                            if(value.getCode() == 0 && value.getData()!=null){
                                choosePath.addAll(value.getData().getImage());
                                updateMV();
                            }
                        }
                    });
        }
    }

    private void updateMV() {
        multiPictureView.clearItem();
        for(String path:choosePath){
            Uri uri = new Uri.Builder().appendPath(path).build();
            multiPictureView.addItem(uri);
        }
    }

    private void initView() {
        tvPersonNum = (TextView) findViewById(R.id.tv_pesron_num);
        multiPictureView = (MultiPictureView) findViewById(R.id.multi_view);
        et_departure = (TextView) findViewById(R.id.et_departure);
        et_destination = (TextView) findViewById(R.id.et_destination);
        et_time = (TextView) findViewById(R.id.et_time);
        et_info = (EditText) findViewById(R.id.et_info);
        et_name = (EditText) findViewById(R.id.et_name);
        et_phone = (EditText) findViewById(R.id.et_phone);
        tv_publish = (TextView) findViewById(R.id.tv_publish);}


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_publish:
                publishCarInfo();
                break;
            case R.id.et_time:
                showTimePicker();
                break;
            case R.id.et_departure:
                showCityPicker(1);
                break;
            case R.id.et_destination:
                showCityPicker(2);
                break;
        }
    }

    private void showCityPicker(final int type) {
        final List<String> op1 = new ArrayList<>();
        OptionsPickerView pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = op1.get(options1);
                if(type == 1){
                    et_departure.setText(tx);
                }else if(type == 2){
                    et_destination.setText(tx);
                }
                ToastUtil.showToast(tx);
            }
        }).setTitleText("城市")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x00000000) //设置外部遮罩颜色
                .build();
        for(CarCity carCity:carCities){
            op1.add(carCity.getCity());
        }
        pvOptions.setPicker(op1);
        pvOptions.show();
    }

    private void showTimePicker() {
        TimePickerView pvTime = new TimePickerBuilder(mActivity, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                Toast.makeText(mActivity, getTime(date), Toast.LENGTH_SHORT).show();
                et_time.setText(getTime(date));
            }
        }).setType(new boolean[]{false, true, true, true, true, false})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .build();
        pvTime.show();
    }

    private void publishCarInfo() {
        String phone = et_phone.getText().toString();
        String name = et_name.getText().toString();
        String remark = et_info.getText().toString();
        String timeString = et_time.getText().toString();
        String departure = et_departure.getText().toString();
        String destination = et_destination.getText().toString();
        String personNum = tvPersonNum.getText().toString();
        if(TextUtils.isEmpty(name)){
            ToastUtil.showToast("请输入你的名字！");
            return;
        }

        if(TextUtils.isEmpty(phone)){
            ToastUtil.showToast("请输入电话号码！");
            return;
        }

        if(TextUtils.isEmpty(timeString)){
            ToastUtil.showToast("请输入你的出发时间哦！");
            return;
        }

        if(TextUtils.isEmpty(departure)){
            ToastUtil.showToast("请输入你的出发城市哦！");
            return;
        }


        if(TextUtils.isEmpty(destination)){
            ToastUtil.showToast("请输入你的目的地城市哦！");
            return;
        }
        if(TextUtils.isEmpty(personNum)){
            ToastUtil.showToast("请选择出行人数哦！");
            return;
        }else{
            personNum=personNum.substring(0,personNum.length()-1);
        }
        if(remark == null){
            remark = "";
        }
        Map<String, Object> param = NetTool.newParams();
        param.put("type",1);
        param.put("departure",departure);
        param.put("destination",destination);
        param.put("go_time",timeString);
        param.put("num",personNum);
        param.put("name",name);
        param.put("phone",phone);
        param.put("remark",remark);
        param.put("image",getImgsSring());
        NetTool.getApi().publishCarInfo(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<OperateResponseBean2>>(this) {
                    @Override
                    public void onData(BaseResponse<OperateResponseBean2> value) {
                        if(value.getCode() == 0 && value.getData()!=null){
                            if(value.getData().isSuccess()){
                                AlertDialog.Builder dialog = new AlertDialog.Builder(mActivity);
                                dialog.setMessage("发布成功！").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                                resetUi();
                                            }
                                        });
                                dialog.show();
                            }else{
                                ToastUtil.showToast(value.getData().getMessage());
                            }
                        }
                    }
                });
    }

    private void resetUi() {
        choosePath.clear();
        multiPictureView.clearItem();
        et_departure.setText("");
        et_destination.setText("");
        et_time.setText("");
        tvPersonNum.setText("");
        et_info.setText("");
        et_phone.setText("");
        et_name.setText("");
    }

    private String getImgsSring() {
        String imgs = "";
        for(String path:choosePath){
            imgs= imgs+path+"@";
        }
        return imgs;
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
        return format.format(date);
    }
}
